package com.hurl.library.spider;

import com.hurl.library.util.StringUtils;

public class NumberRule implements UrlRule{
	private int minValue;
	private int maxValue;
	private int interval = 1;
	private int numberOfDigits = 1;
	private boolean descOrder = false;
	
	private int nextInt;
	private String previous;
	
	public NumberRule(int minValue,int maxValue){
		if(minValue<0){
			throw new ConfigurationException("最小值不能为负数！");
		}
		if(maxValue<0){
			throw new ConfigurationException("最大值不能为负数！");
		}
		if(minValue>maxValue){
			throw new ConfigurationException("最小值不能大雨最大值！");
		}
		this.maxValue=maxValue;
		this.minValue=minValue;
		beforeFirst();
	}
	public NumberRule(int minValue,int maxValue,int interval,int numberOfDigits,boolean descOrder){
		if(minValue>maxValue){
			throw new ConfigurationException("最小值不能大雨最大值！");
		}
		this.maxValue=maxValue;
		this.minValue=minValue;
		if(interval<=0){
			throw new ConfigurationException("间隔值必须为大于0的整数！");
		}
		this.interval=interval;
		if(numberOfDigits<=0){
			throw new ConfigurationException("位数必须为大于0的整数！");
		}
		this.numberOfDigits=numberOfDigits;
		this.descOrder=descOrder;
		beforeFirst();
	}
	
	public void beforeFirst(){
		previous = null;
		if(this.descOrder){
			nextInt=maxValue;
		}else{
			nextInt=minValue;
		}
	}
	public boolean hasNext(){
		if(descOrder){
			return nextInt>=minValue;
		}else{
			return nextInt<=maxValue;
		}
	}
	public String next(){
		if(!hasNext()){
			return null;
		}
		String res = StringUtils.fillPlaces(nextInt, this.numberOfDigits);
		this.previous=res;
		if(descOrder){
			nextInt=nextInt-interval;
		}else{
			nextInt=nextInt+interval;
		}
		return res;
	}
	@Override
	public String previous() {
		return previous;
	}
}
